<template>
  <div class="share">
    <div class="header">
      <div class="header-content">
        <div class="logo" @click="jump">
          <span class="iconfont icon-pan"></span>
          <span class="name">畅联网盘</span>
        </div>
      </div>
    </div>
    <div class="share-body">
      <template v-if="Object.keys(shareInfo).length == 0">
        <div v-loading="Object.keys(shareInfo).length == 0" class="loading"></div>
      </template>
      <template v-else>
        <div class="share-panel">
          <div class="share-user-info">
            <div class="avatar">
              <Avatar :userId="shareInfo.userId" :avatar="shareInfo.photo" :width="50"></Avatar>
            </div>
            <div class="share-info">
              <div class="user-info">
                <span class="nick-name">{{ shareInfo.username }} </span>
                <span class="share-time">分享于 {{ shareInfo.createTime }}</span>
              </div>
              <div class="file-name">分享文件：{{ shareInfo.fileName }}</div>
            </div>
          </div>
          <div class="share-op-btn">
            <el-button type="primary" v-if="shareInfo.currentUser" @click="cancelShare"><span
                class="iconfont icon-cancel"></span>取消分享</el-button>
            <el-button v-else type="primary" @click="OpenMyPan()" :disabled="selectedFileIds.length === 0"><span
                class="iconfont icon-import"></span>保存到我的网盘</el-button>
          </div>
        </div>

        <div class="breadcrumb">
          <span v-for="(item, index) in breadcrumb" :key="item.fileId">
            <a @click="navigateToFolder(item.fileId)">{{ item.fileName }}</a>
            <span v-if="index < breadcrumb.length - 1"> / </span>
          </span>
        </div>

        <div class="file-list">
          <el-table ref="tableRef" :data="files" style="width: 100%" stripe @selection-change="onRowSelected">
            <el-table-column type="selection" width="50"></el-table-column>

            <el-table-column label="文件名" prop="fileName" width="150" align="center">
              <template #default="{ row }">
                <div class="file-item" @click="handleFileClick(row)">
                  <icon :fileType="row.fileType"></icon>
                  <span class="file-name cursor-pointer" :title="row.fileName">{{ row.fileName }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label=" " width="400" align="center">
              <template #default="{ row }">
                <span class="op">

                  <span v-if="row.isFolder == 0" class="iconfont icon-download cursor-pointer"
                    @click="download(row)">下载</span> &nbsp;&nbsp;
                  <span class="iconfont icon-import cursor-pointer" @click="OpenMyPan2(row.fileId)">保存到我的网盘</span>
                </span>
              </template>
            </el-table-column>

            <el-table-column label="时间" prop="fileTime" width="200" align="center">
              <template #default="{ row }">
                <span class="cursor-pointer">{{ row.uploadTime }}</span>
              </template>
            </el-table-column>



            <el-table-column label="大小" prop="fileSize" width="auto" align="center">
              <template #default="{ row }">
                <span v-if="!row.isFolder">{{ formatFileSize(row.fileSize) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

      </template>
    </div>
  </div>

  <!-- 打开自己的网盘 -->
  <el-dialog v-model="dialogTableVisible" title="请选择你要保存的位置" width="500">
    <div class="breadcrumb">
      <span v-for="(item, index) in breadcrumb2" :key="item.fileId">
        <a @click="navigateToFolder2(item.fileId)">{{ item.fileName }}</a>
        <span v-if="index < breadcrumb2.length - 1"> / </span>
      </span>
    </div>

    <div class="file-list">
      <el-table ref="tableRef" :data="files2" style="width: 100%" stripe>
        <el-table-column width="50"></el-table-column>

        <el-table-column label="文件名" prop="fileName" align="center">
          <template #default="{ row }">
            <div class="file-item" @click="handleFileClick2(row)">
              <icon :fileType="row.fileType"></icon>
              <span class="file-name cursor-pointer" :title="row.fileName">{{ row.fileName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center">
          <template #default="{ row }">
            <el-button plain @click="saveMyPan(row)">保存到我的网盘</el-button>
          </template>
        </el-table-column>


      </el-table>
    </div>
  </el-dialog>

</template>

<script setup>
import http from "@/utils/http.js";

import { ref, reactive, getCurrentInstance, watch, onMounted, } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElLoading } from 'element-plus'
const { proxy } = getCurrentInstance();
const router = useRouter();

// 当前目录 ID 和面包屑导航
const currentFolderId = ref(0);
const breadcrumb = ref([{ fileName: "根目录", fileId: 0 }]);
//文件列表
const files = ref([]);

// 文件列表
const mockFiles = ref([]);
onMounted(async () => {
  await checkShare();
  await getShareFile();
  await loadFolderContents(currentFolderId.value);
});

// 多选
const selectedFileIds = ref([]);
const onRowSelected = (rows) => {
  console.log(rows);
  selectedFileIds.value = rows.map((row) => row.fileId);
};

// 加载目录内容
const loadFolderContents = async (folderId) => {
  const result = mockFiles.value.filter(file => file.parentId === folderId);
  files.value = result;
};

// 格式化文件大小
const formatFileSize = (size) => {
  if(size > 1024*1024){
    size = (size/1024/1024).toFixed(2) + 'MB'
        }
        else if(size == 0 || size == null){
          size = ' '
        }
        else{
          size = (size/1024).toFixed(2) + 'KB'
        }

  return size;
};



// 处理文件点击
const handleFileClick = (file) => {
  if (file.isFolder) {
    currentFolderId.value = file.fileId;
    breadcrumb.value.push({ fileName: file.fileName, fileId: file.fileId });
    loadFolderContents(file.fileId);
  }
};

// 面包屑导航跳转
const navigateToFolder = (folderId) => {
  const index = breadcrumb.value.findIndex(item => item.fileId === folderId);
  breadcrumb.value = breadcrumb.value.slice(0, index + 1);
  currentFolderId.value = folderId;
  loadFolderContents(folderId);
};

const shareId = ref('');
const shareInfo = ref({});



const checkShare = async () => {
  const currentUrl = window.location.href;
  const parts = currentUrl.split("/");
  const shareLink = parts[parts.length - 1];
  let result = await http.get('shares/checkShare/' + shareLink);
  if (result.code === 412) {
    proxy.Message.warning(result.msg);
    router.push("/shareCheck/" + shareLink.split("?")[0]);
  } else if (result.code === 413) {
    proxy.Message.warning(result.msg);
    router.push('/main');
  } else {
    shareInfo.value = result.data;
    shareInfo.value.photo = import.meta.env.VITE_API_URL + "/api/v1/File/download/" + shareInfo.value.photo
    shareId.value = result.data.shareId;
  }
};


//下载文件
const download = (file) => {
  // 创建一个 AbortController 实例，用于取消请求
  const controller = new AbortController();
  const signal = controller.signal;

  // 显示“下载中”的弹窗，并添加取消按钮
  const loading = ElLoading.service({
    text: '文件下载，请稍候...', // 弹窗内容
    spinner: 'el-icon-loading',    // 自定义加载样式
    background: 'rgba(0, 0, 0, 0.7)',
    customClass: 'custom-loading-class', // 自定义样式类
    closeOnClickModal: false, // 点击遮罩不关闭
  });

  // 延迟插入取消按钮
  setTimeout(() => {
    const loadingElement = document.querySelector('.custom-loading-class .el-loading-spinner');
    if (loadingElement) {
      // 创建一个容器，包含下载进度和取消按钮
      const actionContainer = document.createElement('div');
      actionContainer.className = 'action-container';

      // 创建取消按钮
      const cancelButton = document.createElement('button');
      cancelButton.textContent = '取消下载';
      cancelButton.className = 'cancel-button'; // 样式类名，可自行定义
      cancelButton.onclick = () => {
        controller.abort(); // 取消请求
        loading.close(); // 关闭加载框
        ElMessage.warning('下载已取消');
      };

      // 添加按钮到容器中
      actionContainer.appendChild(cancelButton);

      // 插入到弹窗中
      loadingElement.appendChild(actionContainer);
    }
  }, 100);

  http({
    method: 'post',
    url: '/files/downLoadFile',
    data: file,
    responseType: 'blob',
    timeout: 600000, // 设置响应超时
    signal, // 将 signal 传入请求
    onDownloadProgress: (progressEvent) => {
      // 计算下载进度
      if (progressEvent.lengthComputable) {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        console.log('下载进度：', percentCompleted + '%');
        loading.setText(`下载中... ${percentCompleted}%`);
      }
    }
  })
    .then(response => {
      if (response) {
        const blob = response;
        const downloadUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;

        // 设置下载的文件名   
        link.download = file.fileName || 'downloaded_file';

        // 触发下载
        link.click();

        // 释放内存
        URL.revokeObjectURL(downloadUrl);

        ElMessage.success('文件下载成功！');
      } else {
        ElMessage.error('文件下载失败！');
      }
    })
    .catch(error => {
      if (error.name === 'AbortError') {
        console.log('下载已取消');
      } else {
        console.error('下载文件时出错：', error);
        ElMessage.error('文件下载失败！');
      }
    })
    .finally(() => {
      loading.close(); // 确保关闭加载提示框
    });
};
  


//取消分享
const cancelShare = () => {
  proxy.Confirm(`你确定要取消分享吗？`, async () => {
    let result = await http.get(
      'shares/cancelShare',
      {
        params: {
          shareId: shareId.value,
        }
      }

    );
    if (!result) {
      return;
    }
    proxy.Message.success("取消分享成功");
    router.push("/main");
  });
};

//通过分享id获取分享文件
const getShareFile = async () => {
  const result = await http.get(
    'shares/searchByFileId',
    {
      params: {
        fileId: shareInfo.value.fileId,
      }
    }
  )
  if (result.code === 414) {
    proxy.Message.warning(result.msg);
    router.push('/main');
  }
  mockFiles.value = result.data;
  const minParentId = mockFiles.value.reduce((min, item) => {
    return (item.parentId < min) ? item.parentId : min;
  }, Number.MAX_VALUE);

  currentFolderId.value = minParentId;
  breadcrumb.value = [{ fileName: "根目录", fileId: minParentId }];

  // 此时 minParentId 为 mockFiles 中 parentId 的最小值
};

const jump = () => {
  router.push("/main");
};


const dialogTableVisible = ref(false)
//保存到我的网盘
const OpenMyPan = async () => {
  console.log(selectedFileIds.value);
  dialogTableVisible.value = true;
  //获取所有文件夹列表
  const result = await http.get('shares/getAllFolderList')
  mockFiles2.value = result.data;
  const minParentId = mockFiles2.value.reduce((min, item) => {
    return (item.parentId < min) ? item.parentId : min;
  }, Number.MAX_VALUE);
  currentFolderId.value = minParentId;
  breadcrumb2.value = [{ fileName: "根目录", fileId: minParentId }];
  loadFolderContents2(minParentId);
};

const OpenMyPan2 = async (id) => {
  selectedFileIds.value = [];
  selectedFileIds.value.push(id);
  await OpenMyPan();
};

// 当前目录 ID 和面包屑导航
const currentFolderId2 = ref(0);
const breadcrumb2 = ref();

//自己的文件列表
const mockFiles2 = ref([]);
const files2 = ref([]);
// 加载目录内容
const loadFolderContents2 = async (folderId) => {
  const result = mockFiles2.value.filter(file => file.parentId === folderId);
  files2.value = result;
};

// 处理文件点击
const handleFileClick2 = (file) => {
  if (file.isFolder) {
    currentFolderId2.value = file.fileId;
    breadcrumb2.value.push({ fileName: file.fileName, fileId: file.fileId });
    loadFolderContents2(file.fileId);
  }
};

// 面包屑导航跳转
const navigateToFolder2 = (folderId) => {
  const index = breadcrumb2.value.findIndex(item => item.fileId === folderId);
  breadcrumb2.value = breadcrumb2.value.slice(0, index + 1);
  currentFolderId2.value = folderId;
  loadFolderContents2(folderId);
};


//保存到我的网盘
const saveMyPan = async (file) => {
  // 创建一个 AbortController 实例，用于取消请求
  const controller = new AbortController();
  const signal = controller.signal;

  // 显示“下载中”的弹窗，并添加取消按钮
  const loading = ElLoading.service({
    text: '文件保存中，请稍候...', // 弹窗内容
    spinner: 'el-icon-loading',    // 自定义加载样式
    background: 'rgba(0, 0, 0, 0.7)',
    customClass: 'custom-loading-class', // 自定义样式类
    closeOnClickModal: false, // 点击遮罩不关闭
  });

  // 延迟插入取消按钮
  setTimeout(() => {
    const loadingElement = document.querySelector('.custom-loading-class .el-loading-spinner');
    if (loadingElement) {
      // 创建一个容器，包含下载进度和取消按钮
      const actionContainer = document.createElement('div');
      actionContainer.className = 'action-container';

      // 创建取消按钮
      const cancelButton = document.createElement('button');
      cancelButton.textContent = '取消保存';
      cancelButton.className = 'cancel-button'; // 样式类名，可自行定义
      cancelButton.onclick = () => {
        controller.abort(); // 取消请求
        loading.close(); // 关闭加载框
        ElMessage.warning('保存已取消');
      };

      // 添加按钮到容器中
      actionContainer.appendChild(cancelButton);

      // 插入到弹窗中
      loadingElement.appendChild(actionContainer);
    }
  }, 100);
  console.log(file);
  console.log(selectedFileIds.value);
  // await http('shares/saveMyPan',
  //   {
  //     params: {
  //       myFileId: file.fileId,
  //       shareId: selectedFileIds.value.join(',')
  //     }
  //   }
  // ).finally(() => {
  //   loading.close();

  
  // });
  http({
    method: 'get',
    url: '/shares/saveMyPan',
    signal,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    params: {
        myFileId: file.fileId,
        shareId: selectedFileIds.value.join(',')
    }
  }).finally(() => {
    loading.close();
  });
  dialogTableVisible.value = false;
  proxy.Message.success("保存成功");
};
</script>


<style lang="scss">
@import "@/assets/file.list.scss";

.header {
  width: 100%;
  position: fixed;
  background: #0c95f7;
  height: 50px;

  .header-content {
    width: 70%;
    margin: 0px auto;
    color: #fff;
    line-height: 50px;

    .logo {
      display: flex;
      align-items: center;
      cursor: pointer;

      .icon-pan {
        font-size: 40px;
      }

      .name {
        font-weight: bold;
        margin-left: 5px;
        font-size: 25px;
      }
    }
  }
}

.cursor-pointer {
  cursor: pointer;
}

.share-body {
  width: 70%;
  margin: 0px auto;
  padding-top: 50px;

  .loading {
    height: calc(100vh / 2);
    width: 100%;
  }

  .share-panel {
    margin-top: 20px;
    display: flex;
    justify-content: space-around;
    border-bottom: 1px solid #ddd;
    padding-bottom: 10px;

    .share-user-info {
      flex: 1;
      display: flex;
      align-items: center;

      .avatar {
        margin-right: 5px;
      }

      .share-info {
        .user-info {
          display: flex;
          align-items: center;

          .nick-name {
            font-size: 15px;
          }

          .share-time {
            margin-left: 20px;
            font-size: 12px;
          }
        }

        .file-name {
          margin-top: 10px;
          font-size: 12px;
        }
      }
    }
  }
}

.file-list {
  margin-top: 10px;

  .file-item {
    .op {
      width: 170px;
    }
  }
}
/* 容器样式 */
.action-container {
  display: flex;
  justify-content: center;
  margin-top: 15px; /* 与进度条的间距 */
}

/* 按钮样式 */
.cancel-button {
  padding: 8px 20px !important;
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  background-color: #f56c6c;
  border: 1px solid #f56c6c;
  border-radius: 20px; /* 圆润的边框 */
  cursor: pointer;
  transition: all 0.3s ease; /* 添加平滑过渡效果 */
  outline: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
}

.cancel-button:hover {
  background-color: #ff7b7b; /* 鼠标悬停时背景颜色 */
  border-color: #ff7b7b; /* 悬停时边框颜色 */
}

.cancel-button:active {
  background-color: #d9534f; /* 按下时背景颜色 */
  border-color: #d9534f; /* 按下时边框颜色 */
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15); /* 按下时内部阴影 */
}
</style>
